package io.renren.modules.sys.annotation;

import io.lettuce.core.dynamic.support.MethodParameter;
import io.renren.modules.sys.common.CommonDataService;
import io.renren.modules.sys.common.CurrentUser;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: weihongyang
 * @Date: 2019/4/24 14:41
 * @Version 1.0
 * CurrentUserData 注解的方法参数解析器，实现 CurrentUserData 注解。
 */
public class UserAnnotationMethodArgumentResolver {
    @Autowired
    private CommonDataService commonDataService;


    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(User.class);
    }


    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest webRequest, WebDataBinderFactory factory) throws Exception {
        String token = webRequest.getHeader("access-token");

        if (StringUtils.isEmpty(token)) {
            token = webRequest.getHeader("token");
        }

        if (StringUtils.isEmpty(token)) {
            return null;
        }

        //有可能 commonDataService 为 null
        if (null == commonDataService) {
            HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
            BeanFactory beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            commonDataService = (CommonDataService) beanFactory.getBean("commonDataService");
        }

        CurrentUser currentUser = commonDataService.getCurrentUserDataFromRedis(token);
        return currentUser;
    }
}
